import pygame

class Jiong(pygame.sprite.Sprite):
    LEFT = 0
    RIGHT = 1
    TOP = 2
    BOTTOM = 3
    
    # img (surface): not none
    # frame (surface list)
    # rate (integer): >= 1    
    def __init__(self, img, pos = (0, 0), frame = None, rate = 3):
        # for super
        pygame.sprite.Sprite.__init__(self)
        # for group
        self.image = img
        self.rect = self.image.get_rect(topleft = pos)
        # for update
        self.__frame = frame
        self.__rate = rate
        self.__count = 0
        self.__index = 0
        self.__action = []
        self.__coll = ()
        """
        self.__exactrect = pygame.Rect(self.rect.left * 100, \
                                       self.rect.top * 100, \
                                       self.rect.width * 100, \
                                       self.rect.height * 100)
        """
    
    def update(self):
        if self.__frame and len(self.__action) > 0:
            self.__count = (self.__count + 1) % self.__rate
            if self.__count == 0: self.__index = (self.__index + 1) % len(self.__frame)
            self.image = self.__frame[self.__index]
        self.__action = []
    
    def __collision_side(self, (dx, dy), sprrc, collrc):
        if dx > 0 and sprrc.right - collrc.left <= dx: return Jiong.LEFT
        elif dx < 0 and sprrc.left - collrc.right >= dx: return Jiong.RIGHT
        elif dy > 0 and sprrc.bottom - collrc.top <= dy: return Jiong.TOP
        elif dy < 0 and sprrc.top - collrc.bottom >= dy: return Jiong.BOTTOM
    
    # (dx, dy) : integer
    # return 1: collision list (spr, side), can be empty
    def __collision_test(self, (dx, dy)):
        rc = self.rect.move(dx, dy)
        groups = self.groups()
        coll = []
        for group in groups:
            for spr in group:
                if (not (spr is self)) and rc.colliderect(spr.rect):
                    coll.append((spr, self.__collision_side((dx, dy), rc, spr.rect)))                
        return tuple(coll)
    
    # (dx, dy) : integer
    # return : collision list (spr, side), can be empty
    def move(self, (dx, dy)):
        coll = self.__collision_test((dx, dy))
        if len(coll) == 0:
            self.rect.move_ip(dx, dy)
            """
            self.__exactrect.move_ip(dx * 100, dy * 100)
            self.rect = pygame.Rect(self.__exactrect.left / 100, \
                                    self.__exactrect.top / 100, \
                                    self.__exactrect.width / 100, \
                                    self.__exactrect.height / 100)
            """
        self.__coll = coll
        return coll
    
    def get_coll(self):
        return self.__coll
    
    # keyname: in pygame.locals
    def action(self, keyname):
        self.__action.append(keyname)
  
    
    
    